package org.darcy.service.work.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.darcy.entity.CheckCollect;
import org.darcy.entity.CheckDelivery;
import org.darcy.entity.CheckLibAnalysis;
import org.darcy.entity.WorkRoleUser;
import org.darcy.entity.business.BusinessContract;
import org.darcy.entity.business.BusinessFinancialReceived;
import org.darcy.entity.check.ContractRequirement;
import org.darcy.entity.work.WorkInstance;
import org.darcy.entity.work.WorkTask;
import org.darcy.framework.constant.BusinessType;
import org.darcy.framework.constant.SysConstant;
import org.darcy.service.business.BusinessContractService;
import org.darcy.service.business.BusinessFinancialReceivedService;
import org.darcy.service.check.CheckCollectService;
import org.darcy.service.check.CheckDeliveryService;
import org.darcy.service.flow.FlowLeaveCompanyService;
import org.darcy.service.org.OrgDepartmentService;
import org.darcy.service.privilege.SysUserService;
import org.darcy.service.work.WorkRoleUserService;
import org.darcy.service.work.WorkService;
import org.darcy.service.work.WorkTaskService;
import org.darcy.vo.ContractAmount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

/**
 * 审批通过后，生成下一工作项（本系统的主要业务逻辑）
 */
@Service
@Slf4j
public class WorkNextService {

	@Autowired
	private WorkService WorkService;

	@Autowired
	private WorkTaskService WorkTaskService;

	@Autowired
	@Lazy
	private BusinessContractService BusinessContractService;

	@Autowired
	@Lazy
	private CheckDeliveryService CheckDeliveryService;

	@Autowired
	@Lazy
	private CheckCollectService CheckCollectService;

	@Autowired
	@Lazy
	private BusinessFinancialReceivedService BusinessFinancialReceivedService;

	@Autowired
	@Lazy
	private WorkRoleUserService WorkRoleUserService;

	@Autowired
	@Lazy
	private SysUserService SysUserService;

	@Autowired
	@Lazy
	private OrgDepartmentService OrgDepartmentService;

	@Autowired
	@Lazy
	private FlowLeaveCompanyService FlowLeaveCompanyService;

	/**
	 * 审批通过，生成下一个待办事项
	 * 
	 * @param record 当前工作任务
	 */
	public void createNext(WorkInstance record) {
		Integer id = record.getFormId();
		switch (record.getFormType()) {
		// 1.合同登记审批通过，生成：合同确认、派工单、合同收款
		case SysConstant.FormType.BusinessContract:
			createBusinessContractNext(id);
			break;
		// 2.合同确认审批通过，结束
		case SysConstant.FormType.ContractConfirm:
			break;
		// 3.合同收款审批通过，款项没有全部收齐，则再次生成合同收款
		case SysConstant.FormType.FinancialReceived:
			createFinancialReceivedNext(id);
			break;
		// 1.派工单审批通过，生成：采样or场调or...
		case SysConstant.FormType.CheckDelivery:
			createCheckDeliveryNext(id);
			break;
		// 2.场调审批通过，生成：采样
		case SysConstant.FormType.CheckChangDiao1:
			createCheckChangDiaoNext(id);
			break;
		// 2.场调审批通过，生成：采样
		case SysConstant.FormType.CheckChangDiao2:
			createCheckChangDiaoNext(id);
			break;
		// 2.采样审批通过，生成：收样
		case SysConstant.FormType.CheckCaiYang:
			createCheckCaiYangNext(id);
			break;
		case SysConstant.FormType.CheckShouYang:
			// createCheckShouYangNext(id);
			break;
		case SysConstant.FormType.CheckService:
			createCheckServiceNext(id);
			break;
		case SysConstant.FormType.LibDispatch:
			// createLibDispatchNext(id);
			break;
		case SysConstant.FormType.LibAnalysis:
			break;
		case SysConstant.FormType.LibReport:
			createLibReportNext(id);
			break;
		case SysConstant.FormType.CheckReport:
			createCheckReportNext(id);
			break;
		case SysConstant.FormType.ShowPublic:
			// createShowPublicNext(id);
			break;
		case SysConstant.FormType.HandOver:
			// createHandOverNext(id);
			break;
		case SysConstant.FormType.CloseDept:
			// createCloseDeptNext(id);
			break;
		case SysConstant.FormType.CloseFinancial:
			// createCloseFinancialNext(id);
			break;
		case SysConstant.FormType.Archive:
			log.debug("项目归档结束");
			break;
		case SysConstant.FormType.LeaveCompany:
			log.debug("离职交接");
			createLeaveCompanyNext(id);
			break;
		default:
			return;
		}

	}

	/**
	 * 生成下一个工作项
	 */
	private Integer createWork(String formType, Integer formId, Integer groupId, String title, String summary,
			String operatorName) {
		WorkInstance next = new WorkInstance();
		next.setFormType(formType);
		next.setFormId(formId);
		next.setGroupId(groupId);
		next.setStartTime(new Date());
		next.setTitle(title);
		next.setSummary(summary);
		next.setOperatorName(operatorName);
		WorkService.insert(next);
		return next.getId();
	}

	/**
	 * 生成下一个工作任务
	 */
	private Integer createTask(Integer workId, String comment, Integer operator, String operatorName) {
		WorkTask draft = new WorkTask();
		draft.setWorkId(workId);
		draft.setOperator(operator);
		draft.setOperatorName(operatorName);
		draft.setComment(comment);
		WorkTaskService.insert(draft);
		return draft.getId();
	}

	/**
	 * 合同登记审批通过，生成下一个待办事项
	 * 
	 * @param contractId 合同id
	 */
	private void createBusinessContractNext(Integer contractId) {
		BusinessContract data = BusinessContractService.getDetail(contractId);

		// 1.合同确认
		String title = null;
		String summary = null;
		Integer operator = data.getProjectOperator();
		String operatorName = data.getProjectOperatorName();

		title = String.format("[%s]的合同确认", data.getProjectOperatorName());
		summary = String.format("合同编号：%s\n委托单位：%s\n委托业务：%s\n经办人：%s", data.getFormNo(), data.getClientName(),
				data.getProjectType(), data.getProjectOperatorName());
		Integer workId = createWork(SysConstant.FormType.ContractConfirm, contractId, contractId, title, summary,
				operatorName);
		createTask(workId, title, operator, operatorName);

		// 2.派工单（多个）
		for (String type : data.getProjectTypeList()) {
			CheckDelivery delivery = new CheckDelivery();
			delivery.setContractId(contractId);
			delivery.setProjectManager(operator);
			delivery.setItemName(type);
			// 费用
			List<ContractAmount> feeList = data.getContractAmountList();
			for (ContractAmount a : feeList) {
				if (a.getName().equals(type)) {
					delivery.setItemCapital(a.getValue());
				}
			}
			// 默认添加专家费
			List<ContractRequirement> contractRequirementList = new ArrayList<ContractRequirement>();
			ContractRequirement r = new ContractRequirement();
			r.setType("专家费");
			r.setAmount(0f);
			contractRequirementList.add(r);
			delivery.setContractRequirementList(contractRequirementList);

			CheckDeliveryService.insert(delivery);

			title = String.format("[%s]的派工单", data.getProjectOperatorName());
			summary = String.format("合同编号：%s\n委托单位：%s\n委托业务：%s\n经办人：%s", data.getFormNo(), data.getClientName(), type,
					data.getProjectOperatorName());
			// createTask(SysConstant.FormType.CheckDelivery, delivery.getId(), title,
			// summary, operator, operatorName);
			workId = createWork(SysConstant.FormType.CheckDelivery, delivery.getId(), contractId, title, summary,
					operatorName);
			createTask(workId, title, operator, operatorName);

		}

		// 3.合同收款
		BusinessFinancialReceived recv = new BusinessFinancialReceived();
		recv.setContractId(contractId);
		recv.setBusinessType(data.getProjectType());
		BusinessFinancialReceivedService.insert(recv);

		title = String.format("[%s]的合同收款", data.getProjectOperatorName());
		summary = String.format("合同编号：%s\n委托单位：%s\n委托业务：%s\n经办人：%s", data.getFormNo(), data.getClientName(),
				data.getProjectType(), data.getProjectOperatorName());
		// createTask(SysConstant.FormType.FinancialReceived, recv.getId(), title,
		// summary, operator, operatorName);
		workId = createWork(SysConstant.FormType.FinancialReceived, recv.getId(), contractId, title, summary,
				operatorName);
		createTask(workId, title, operator, operatorName);
		// end
	}

	/**
	 * 合同收款审批通过，生成下一个待办事项
	 * 
	 * @param id 合同收款id
	 */
	private void createFinancialReceivedNext(Integer id) {
		BusinessFinancialReceived data = BusinessFinancialReceivedService.getDetail(id);
		BusinessContract contract = data.getContract();

		List<BusinessFinancialReceived> list = BusinessFinancialReceivedService.getList(data.getContractId());
		Float receivedTotal = 0f;
		for (BusinessFinancialReceived a : list) {
			receivedTotal += a.getPayAmount();
		}

		if (contract.getContractAmountTotal() > receivedTotal) {
			log.debug("收款没有全部完成");
			BusinessFinancialReceived recv = new BusinessFinancialReceived();
			recv.setContractId(contract.getId());
			recv.setBusinessType(contract.getProjectType());
			BusinessFinancialReceivedService.insert(recv);

			Integer operator = contract.getProjectOperator();
			String operatorName = contract.getProjectOperatorName();
			String title = String.format("[%s]的合同收款", contract.getProjectOperatorName());
			String summary = String.format("合同编号：%s\n委托单位：%s\n委托业务：%s\n经办人：%s", contract.getFormNo(),
					contract.getClientName(), contract.getProjectType(), contract.getProjectOperatorName());
			// createTask(SysConstant.FormType.FinancialReceived, recv.getId(), title,
			// summary, operator, operatorName);
			Integer workId = createWork(SysConstant.FormType.FinancialReceived, recv.getId(), contract.getId(), title,
					summary, operatorName);
			createTask(workId, title, operator, operatorName);

		} else {
			log.debug("收款完成");
		}

	}

	/**
	 * 派工单审批通过，生成下一个待办事项：场调or采样or收样or现场服务
	 * 
	 * @param id 派工单id
	 */
	private void createCheckDeliveryNext(Integer id) {
		CheckDelivery data = CheckDeliveryService.getDetail(id);
		Integer contractId = data.getContractId();
		String formType = null;
		String title = null;
		String summary = null;

		if (data.getItemName().equals("职业卫生")) {
			formType = SysConstant.FormType.CheckChangDiao1;
		} else if (data.getItemName().equals("验收")) {
			formType = SysConstant.FormType.CheckChangDiao2;
		} else if (data.getItemName().equals("委托检测") || data.getItemName().equals("年度委托检测")) {
			formType = SysConstant.FormType.CheckCaiYang;
		} else if (data.getItemName().equals("来样检测")) {
			formType = SysConstant.FormType.CheckShouYang;
		} else if (data.getItemName().equals("安全托管") || data.getItemName().equals("环保管家")) {
			formType = SysConstant.FormType.CheckService;
		} else {
			formType = SysConstant.FormType.CheckReport;
		}

		Integer collectId = id;// 第一次服务的采样id，其中职业卫生、验收只有1次
		for (int i = 0; i < data.getServiceFrequency(); i++) {
			CheckCollect a = new CheckCollect();
			a.setDeliveryId(id);
			CheckCollectService.insert(a);
			if (i == 0) {
				collectId = a.getId();
			}
		}

		String name = BusinessType.getBusinessName(formType);

		// 采样人员待办事项
		Integer userId = data.getAcceptDept();
		String operatorName = SysUserService.getById(userId).getRealName();
		title = String.format("[%s]的%s", operatorName, name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		Integer workId = createWork(formType, collectId, contractId, title, summary, operatorName);
		createTask(workId, title, userId, operatorName);

		if (formType.equals(SysConstant.FormType.CheckChangDiao1)
				|| formType.equals(SysConstant.FormType.CheckChangDiao2)) {
			return;
		}

		// 综合办公室待办事项
		List<WorkRoleUser> deptUserList = WorkRoleUserService.getManagerList(1, null);
		StringBuffer s = new StringBuffer();
		for (WorkRoleUser user : deptUserList) {
			s.append(user.getRealName()).append(",");
		}
		title = String.format("[%s]的%s", s.toString(), name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		workId = createWork(SysConstant.FormType.CheckCaiYangDept, collectId, contractId, title, summary, s.toString());
		for (WorkRoleUser user : deptUserList) {
			String comment = String.format("[%s]的%s", user.getRealName(), name);
			createTask(workId, comment, user.getUserId(), user.getRealName());
		}
		// end
	}

	/**
	 * 场调审批通过，生成下一个待办事项：采样
	 * 
	 * @param id 采样id
	 */
	private void createCheckChangDiaoNext(Integer id) {
		CheckCollect collect = CheckCollectService.getDetail(id);
		CheckDelivery data = collect.getDelivery();

		String formType = SysConstant.FormType.CheckCaiYang;
		String title = null;
		String summary = null;
		String name = BusinessType.getBusinessName(formType);

		// 采样人员由场调指定
		List<WorkRoleUser> userList = WorkRoleUserService.getManagerList(1, data.getSurveyAccept());
		StringBuffer s = new StringBuffer();
		for (WorkRoleUser user : userList) {
			s.append(user.getRealName()).append(",");
		}
		title = String.format("[%s]的%s", s.toString(), name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		Integer workId = createWork(formType, id, data.getContractId(), title, summary, s.toString());
		for (WorkRoleUser user : userList) {
			String comment = String.format("[%s]的%s", user.getRealName(), name);
			createTask(workId, comment, user.getUserId(), user.getRealName());
		}

		// 综合办公室待办事项
		List<WorkRoleUser> deptUserList = WorkRoleUserService.getManagerList(1, null);
		s = new StringBuffer();
		for (WorkRoleUser user : deptUserList) {
			s.append(user.getRealName()).append(",");
		}
		title = String.format("[%s]的%s", s.toString(), name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		workId = createWork(SysConstant.FormType.CheckCaiYangDept, id, data.getContractId(), title, summary,
				s.toString());
		for (WorkRoleUser user : deptUserList) {
			String comment = String.format("[%s]的%s", user.getRealName(), name);
			createTask(workId, comment, user.getUserId(), user.getRealName());
		}
		// end
	}

	/**
	 * 采样审批通过，生成下一个待办事项：收样or采样+收样
	 * 
	 * @param id 采样id
	 */
	private void createCheckCaiYangNext(Integer id) {
		String formType = null;
		String title = null;
		String summary = null;
		CheckCollect collect = CheckCollectService.getDetailProgress(id, SysConstant.FormType.Archive);
		CheckDelivery data = collect.getDelivery();
		CheckCollect nextCollect = null;
		// 采样服务列表
		List<CheckCollect> collectServiceList = data.getCollectList();
		for (CheckCollect a : collectServiceList) {
			if (a.getId() > id) {
				nextCollect = a;
				break;
			}
		}
		// 1.完成，触发下一次服务，并生成采样任务（下一次服务）和收样任务（本次服务）
		if (collect.getCollectFinished() == 1 && nextCollect != null) {
			formType = SysConstant.FormType.CheckCaiYang;
			String name = BusinessType.getBusinessName(formType);
			// 采样人员待办事项
			WorkTask task = WorkTaskService.getApprovedTask(formType, id);
			title = String.format("[%s]的%s", task.getOperatorName(), name);
			summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(),
					name, data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
					data.getContract().getProjectOperatorName());
			Integer workId = createWork(formType, nextCollect.getId(), data.getContractId(), title, summary,
					task.getOperatorName());
			createTask(workId, title, task.getOperator(), task.getOperatorName());
		}
		// 2.未完成，再次生成采样记录，并生成采样任务和收样任务
		// 3.未采样，再次生成采样记录，并生成采样任务
		if (collect.getCollectFinished() == 0 || collect.getCollectFinished() == -1) {
			CheckCollect child = new CheckCollect();
			// 使得同一组的采样pid相同
			if (collect.getPid() != null) {
				child.setPid(collect.getPid());
			} else {
				child.setPid(id);
			}
			child.setDeliveryId(collect.getDeliveryId());
			CheckCollectService.insert(child);

			formType = SysConstant.FormType.CheckCaiYang;
			String name = BusinessType.getBusinessName(formType);

			// 采样人员待办事项
			WorkTask task = WorkTaskService.getApprovedTask(formType, id);
			title = String.format("[%s]的%s", task.getOperatorName(), name);
			summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(),
					name, data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
					data.getContract().getProjectOperatorName());
			Integer workId = createWork(formType, child.getId(), data.getContractId(), title, summary,
					task.getOperatorName());
			createTask(workId, title, task.getOperator(), task.getOperatorName());

			if (collect.getCollectFinished() == -1) {
				// 收样任务不生成，因此直接返回
				return;
			}
		}

		formType = SysConstant.FormType.CheckShouYang;
		String name = BusinessType.getBusinessName(formType);
		List<WorkRoleUser> userList = WorkRoleUserService.getManagerList(2, data.getAcceptDept());
		StringBuffer s = new StringBuffer();
		for (WorkRoleUser user : userList) {
			s.append(user.getRealName()).append(",");
		}
		title = String.format("[%s]的%s", s.toString(), name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		Integer workId = createWork(formType, id, data.getContractId(), title, summary, s.toString());
		for (WorkRoleUser user : userList) {
			String comment = String.format("[%s]的%s", user.getRealName(), name);
			createTask(workId, comment, user.getUserId(), user.getRealName());
		}
		// end
	}

	/**
	 * 收样提交，生成下一个待办事项：实验派工
	 * 
	 * @param id 采样id
	 */
	public void createCheckShouYangNext(Integer id) {
		CheckCollect collect = CheckCollectService.getDetail(id);
		// 多次采样的，不重复生成实验派工。即：实验派工的次数等于采样服务的次数
		if (collect.getPid() != null) {
			return;
		}
		CheckDelivery data = collect.getDelivery();
		String formType = SysConstant.FormType.LibDispatch;
		String title = null;
		String summary = null;

		String name = BusinessType.getBusinessName(formType);
		List<WorkRoleUser> userList = WorkRoleUserService.getManagerList(3, null);
		StringBuffer s = new StringBuffer();
		for (WorkRoleUser user : userList) {
			s.append(user.getRealName()).append(",");
		}
		title = String.format("[%s]的%s", s.toString(), name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		Integer workId = createWork(formType, id, data.getContractId(), title, summary, s.toString());
		for (WorkRoleUser user : userList) {
			String comment = String.format("[%s]的%s", user.getRealName(), name);
			createTask(workId, comment, user.getUserId(), user.getRealName());
		}
		// end
	}

	/**
	 * 现场服务通过，生成下一个待办事项：结算办公室
	 * 
	 * @param id 采样id
	 */
	private void createCheckServiceNext(Integer id) {
		CheckCollect collect = CheckCollectService.getDetail(id);
		CheckDelivery data = collect.getDelivery();

		String formType = SysConstant.FormType.CloseDept;
		String title = null;
		String summary = null;
		String name = BusinessType.getBusinessName(formType);

		// 综合办公室待办事项
		List<WorkRoleUser> deptUserList = WorkRoleUserService.getManagerList(1, null);
		StringBuffer s = new StringBuffer();
		for (WorkRoleUser user : deptUserList) {
			s.append(user.getRealName()).append(",");
		}
		title = String.format("[%s]的%s", s.toString(), name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		Integer workId = createWork(formType, id, data.getContractId(), title, summary, s.toString());
		for (WorkRoleUser user : deptUserList) {
			String comment = String.format("[%s]的%s", user.getRealName(), name);
			createTask(workId, comment, user.getUserId(), user.getRealName());
		}
		// end
	}

	/**
	 * 实验派工提交，生成下一个待办事项：实验分析，实验报告
	 * 
	 * @param id 采样id
	 */
	public void createLibDispatchNext(Integer id) {
		CheckCollect collect = CheckCollectService.getDetailProgress(id, SysConstant.FormType.LibDispatch);
		CheckDelivery data = collect.getDelivery();
		// 实验分析，不是抢占式，而是每个分析都是单独的工作项
		String formType = SysConstant.FormType.LibAnalysis;
		String title = null;
		String summary = null;
		String name = BusinessType.getBusinessName(formType);

		Integer userId = null;
		String operatorName = null;
		Integer workId = null;

		for (CheckLibAnalysis a : collect.getLibAnalysisList()) {
			userId = a.getManager();
			operatorName = SysUserService.getById(userId).getRealName();
			String comment = String.format("[%s]的%s", operatorName, name);
			title = String.format("[%s]的%s", operatorName, name);
			summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(),
					name, data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
					data.getContract().getProjectOperatorName());
			workId = createWork(formType, a.getId(), data.getContractId(), title, summary, operatorName);
			createTask(workId, comment, userId, operatorName);
		}
		// 实验报告
		formType = SysConstant.FormType.LibReport;
		name = BusinessType.getBusinessName(formType);
		userId = collect.getLibReportManager();
		operatorName = SysUserService.getById(userId).getRealName();
		title = String.format("[%s]的%s", operatorName, name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		workId = createWork(formType, id, data.getContractId(), title, summary, operatorName);
		createTask(workId, title, userId, operatorName);
		// end
	}

	/**
	 * 实验报告审批通过，生成下一个待办事项：交付
	 * 
	 * @param id 采样id
	 */
	private void createLibReportNext(Integer id) {
		CheckCollect collect = CheckCollectService.getDetail(id);
		CheckDelivery data = collect.getDelivery();
		String formType = SysConstant.FormType.HandOver;
		String title = null;
		String summary = null;
		String name = BusinessType.getBusinessName(formType);

		// 如果是职业卫生、验收，则下一步是：报告编制
		if (data.getItemName().equals("职业卫生") || data.getItemName().equals("验收")) {
			formType = SysConstant.FormType.CheckReport;
			name = BusinessType.getBusinessName(formType);
			// 待办事项由场调负责人执行
			Integer uid = 0;
			String operatorName = null;
			String type = SysConstant.FormType.CheckChangDiao1;
			if (data.getItemName().equals("验收")) {
				type = SysConstant.FormType.CheckChangDiao2;
			}
			WorkInstance param = WorkInstance.builder().formType(type).formId(id)
					.status(SysConstant.FlowStatus.STATUS100_APPROVED).build();
			WorkInstance work = WorkService.getBusinessWork(param);
			List<WorkTask> list = WorkTaskService.getTaskList(work.getId());
			for (WorkTask a : list) {
				if (a.getStatus().equals(SysConstant.TaskStatus.STATUS1_DONE)) {
					uid = a.getOperator();
					operatorName = a.getOperatorName();
				}
			}
			title = String.format("[%s]的%s", operatorName, name);
			summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(),
					name, data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
					data.getContract().getProjectOperatorName());
			Integer workId = createWork(formType, id, data.getContractId(), title, summary, operatorName);
			String comment = String.format("[%s]的%s", operatorName, name);
			createTask(workId, comment, uid, operatorName);

			return;
		}

		// 综合办公室待办事项
		List<WorkRoleUser> deptUserList = WorkRoleUserService.getManagerList(1, null);
		StringBuffer s = new StringBuffer();
		for (WorkRoleUser user : deptUserList) {
			s.append(user.getRealName()).append(",");
		}
		title = String.format("[%s]的%s", s.toString(), name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		Integer workId = createWork(formType, id, data.getContractId(), title, summary, s.toString());
		for (WorkRoleUser user : deptUserList) {
			String comment = String.format("[%s]的%s", user.getRealName(), name);
			createTask(workId, comment, user.getUserId(), user.getRealName());
		}
		// end
	}

	/**
	 * 报告编制审批通过，生成下一个待办事项：公示or交付
	 * 
	 * @param id 采样id
	 */
	private void createCheckReportNext(Integer id) {
		CheckCollect collect = CheckCollectService.getDetail(id);
		CheckDelivery data = collect.getDelivery();

		String formType = SysConstant.FormType.ShowPublic;
		if (data.getItemName().equals("职业卫生") || data.getItemName().equals("验收")) {
			formType = SysConstant.FormType.ShowPublic;
		} else {
			formType = SysConstant.FormType.HandOver;
		}

		String title = null;
		String summary = null;
		String name = BusinessType.getBusinessName(formType);

		// 综合办公室待办事项
		List<WorkRoleUser> deptUserList = WorkRoleUserService.getManagerList(1, null);
		StringBuffer s = new StringBuffer();
		for (WorkRoleUser user : deptUserList) {
			s.append(user.getRealName()).append(",");
		}
		title = String.format("[%s]的%s", s.toString(), name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		Integer workId = createWork(formType, id, data.getContractId(), title, summary, s.toString());
		for (WorkRoleUser user : deptUserList) {
			String comment = String.format("[%s]的%s", user.getRealName(), name);
			createTask(workId, comment, user.getUserId(), user.getRealName());
		}
		// end
	}

	/**
	 * 公示提交，生成下一个待办事项：交付
	 * 
	 * @param id 采样id
	 */
	public void createShowPublicNext(Integer id) {
		CheckCollect collect = CheckCollectService.getDetail(id);
		CheckDelivery data = collect.getDelivery();
		String formType = SysConstant.FormType.HandOver;
		String title = null;
		String summary = null;
		String name = BusinessType.getBusinessName(formType);
		// 综合办公室待办事项
		List<WorkRoleUser> deptUserList = WorkRoleUserService.getManagerList(1, null);
		StringBuffer s = new StringBuffer();
		for (WorkRoleUser user : deptUserList) {
			s.append(user.getRealName()).append(",");
		}
		title = String.format("[%s]的%s", s.toString(), name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		Integer workId = createWork(formType, id, data.getContractId(), title, summary, s.toString());
		for (WorkRoleUser user : deptUserList) {
			String comment = String.format("[%s]的%s", user.getRealName(), name);
			createTask(workId, comment, user.getUserId(), user.getRealName());
		}
		// end
	}

	/**
	 * 交付提交，生成下一个待办事项：结算（办公室）
	 * 
	 * @param id 采样id
	 */
	public void createHandOverNext(Integer id) {
		createCheckServiceNext(id);
	}

	/**
	 * 办公室结算提交，生成下一个待办事项：结算（财务）
	 * 
	 * @param id 采样id
	 */
	public void createCloseDeptNext(Integer id) {
		CheckCollect collect = CheckCollectService.getDetail(id);
		CheckDelivery data = collect.getDelivery();

		String formType = SysConstant.FormType.CloseFinancial;
		String title = null;
		String summary = null;
		String name = BusinessType.getBusinessName(formType);

		// 财务室id
		Integer deptId = OrgDepartmentService.getFinancialDept().getId();
		List<WorkRoleUser> deptUserList = WorkRoleUserService.getManagerList(1, deptId);
		StringBuffer s = new StringBuffer();
		for (WorkRoleUser user : deptUserList) {
			s.append(user.getRealName()).append(",");
		}
		title = String.format("[%s]的%s", s.toString(), name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		Integer workId = createWork(formType, id, data.getContractId(), title, summary, s.toString());
		for (WorkRoleUser user : deptUserList) {
			String comment = String.format("[%s]的%s", user.getRealName(), name);
			createTask(workId, comment, user.getUserId(), user.getRealName());
		}
		// end
	}

	/**
	 * 财务结算提交，生成下一个待办事项：归档
	 * 
	 * @param collectData 前端传入的采样信息
	 */
	public void createCloseFinancialNext(CheckCollect collectData) {
		CheckCollect collect = CheckCollectService.getDetailProgress(collectData.getId(), SysConstant.FormType.Archive);
		CheckDelivery data = collect.getDelivery();

		// 判断是否多次服务全部完成，是：则生成归档；否：则跳过
		Boolean isArchive = true;
		// 采样服务列表
		List<CheckCollect> collectServiceList = data.getCollectList();
		for (CheckCollect a : collectServiceList) {
			// 跳过本次的采样，因为前端传入的结算时间还没有入库
			if (a.getId().equals(collectData.getId())) {
				continue;
			}
			if (a.getCloseTime() == null) {
				isArchive = false;
			}
		}

		if (!isArchive) {
			log.info("多次服务未全部完成，跳过归档");
			return;
		}

		String formType = SysConstant.FormType.Archive;
		String title = null;
		String summary = null;
		String name = BusinessType.getBusinessName(formType);

		// 项目经办人
		Integer uid = collect.getDelivery().getContract().getProjectOperator();
		String operatorName = collect.getDelivery().getContract().getProjectOperatorName();
		title = String.format("[%s]的%s", operatorName, name);
		summary = String.format("%s的%s\n业务名称：%s\n服务方式：%s\n服务频次：%s\n经办人：%s", data.getContract().getClientName(), name,
				data.getItemName(), data.getServiceType(), data.getServiceFrequency(),
				data.getContract().getProjectOperatorName());
		Integer workId = createWork(formType, collectData.getId(), data.getContractId(), title, summary, operatorName);
		Integer taskId = createTask(workId, title, uid, operatorName);
		log.info("生成归档任务，workId={}, taskId={}", workId, taskId);
		// end
	}

	/**
	 * 离职交接审批通过：离职者的待办事项转到接收人名下
	 * 
	 * @param id 离职id
	 */
	private void createLeaveCompanyNext(Integer id) {
		FlowLeaveCompanyService.doBusiness(id);
	}

}
